<template>
  <el-upload
    class="avatar-uploader"
    action="/common/upload"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :on-error="handleError"
    :auto-upload="true"
    :before-upload="beforeAvatarUpload"
    :on-change="onChange"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<script>
import { reactive, toRefs } from 'vue'
import { Plus } from '@element-plus/icons-vue'
export default {
  components: {
    Plus
  },
  setup(props, { emit }) {
    const _data = reactive({
      imageUrl: ''
    })
    function onChange(file, fileList) {
      if (file.status === 'success') {
        _data.imageUrl = URL.createObjectURL(file.raw)
        emit('success', file.response.data)
      }
      console.log('onChange', file, fileList)
    }
    function handleAvatarSuccess() {
    }
    function beforeAvatarUpload(file) {
      console.log('beforeAvatarUpload', file)
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        $message.error('上传头像图片大小不能超过 2MB!')
      }
      return true
    }
    function handleError(err) {
      console.log(err, 'handleError')
    }
    return {
      ...toRefs(_data),
      handleAvatarSuccess,
      beforeAvatarUpload,
      handleError,
      onChange
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader {
  ::v-deep .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
}
.avatar-uploader {
  ::v-deep .el-upload:hover {
    border-color: $bar;
  }
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
